package com.cuz.hot100;

public class Q64MinPathSum {
    public static void main(String[] args) {
        //[[1,3,1],[1,5,1],[4,2,1]]
        //[1,2,3],[4,5,6]
        int[][] ints = {
                {1, 2, 3},
                {4, 5, 6},
        };
        System.out.println(minPathSum1(ints));
    }

    public static int minPathSum2(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int rowMax = grid.length;
        int colMax = grid[0].length;
        int[][] dp = new int[rowMax][colMax];
        for (int row = 0; row < rowMax; row++) {
            for (int col = 0; col < colMax; col++) {
                if (row == 0 && col == 0) {
                    dp[row][col] = grid[row][col];
                } else {
                    int ans = Integer.MAX_VALUE;
                    if (row - 1 >= 0) {
                        ans = dp[row - 1][col];
                    }
                    if (col - 1 >= 0) {
                        ans = Math.min(dp[row][col - 1], ans);
                    }
                    dp[row][col] = ans + grid[row][col];
                }
            }
        }
        return dp[rowMax - 1][colMax - 1];
    }

    public static int minPathSum1(int[][] grid) {
        return process(grid, grid.length - 1, grid[0].length - 1);
    }

    //运动到x y 位置的路径和
    private static int process(int[][] grid, int x, int y) {
        if (x == 0 && y == 0) {
            return grid[0][0];
        }
        int ans = Integer.MAX_VALUE;
        if (x - 1 >= 0) {
            ans = process(grid, x - 1, y);
        }
        if (y - 1 >= 0) {
            ans = Math.min(process(grid, x, y - 1), ans);
        }
        return ans + grid[x][y];
    }
}
